import { LANG, TAGS_VIEW } from '@/constant';
import { getItem, setItem } from '@/utils/storage';

export default {
  namespaced: true,
  state: () => ({
    sidebarOpened: true,
    language: getItem(LANG) || 'zh',
    tagsViewList: getItem(TAGS_VIEW) || []
  }),
  mutations: {
    triggerSidebarOpened(state) {
      state.sidebarOpened = !state.sidebarOpened;
    },
    setLanguage(state, lang) {
      setItem(LANG, lang);
      state.language = lang;
    },
    addTagsViewList(state, tag) {
      // 处理重复
      const isFind = state.tagsViewList.find((item) => item.path === tag.path);
      if (!isFind) {
        state.tagsViewList.push(tag);
        setItem(TAGS_VIEW, state.tagsViewList);
      }
    },
    changeTagsView(state, { index, tag }) {
      state.tagsViewList[index] = tag;
      setItem(TAGS_VIEW, state.tagsViewList);
    },
    removeTagsView(state, payload) {
      if (payload.type === 'index') {
        // current
        state.tagsViewList.splice(payload.index, 1);
      } else if (payload.type === 'other') {
        // other
        state.tagsViewList = state.tagsViewList.filter(
          (item, index) => index === payload.index
        );
      } else if (payload.type === 'right') {
        // right
        state.tagsViewList = state.tagsViewList.filter(
          (item, index) => index <= payload.index
        );
      }
      setItem(TAGS_VIEW, state.tagsViewList);
    }
  }
};
